//
//  SingletonTest.m
//  test-workspaces
//
//  Created by 杨岑 on 11/11/14.
//  Copyright (c) 2014 杨岑. All rights reserved.
//
#import "SingletonTest.h"

@implementation SingletonTest
{
    BOOL _initCalled;
}

static SingletonTest* _singleton = nil;

+(instancetype)instance
{
    @synchronized(self)
    {
        NSLog(@"SingletonTest:instance");
        if (!_singleton)
        {
            _singleton = [[SingletonTest alloc] init];
        }
    }
    return _singleton;
}

/*
+ (void)initialize
{
    NSLog(@"SingletonTest:initialize");
    if (self == [SingletonTest self])
    {
        _singleton = [[SingletonTest alloc] init];
    }
}
*/

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    NSLog(@"SingletonTest:alloc");
    @synchronized(self)
    {
        if (!_singleton) _singleton = [super allocWithZone:zone];
    }
    return _singleton;
}

- (instancetype)init
{
    @synchronized(self)
    {
        if (!_initCalled)
        {
            NSLog(@"SingletonTest:init");
            self = [super init];
            if (self != nil) {
                // initialize stuff here
            }
            _initCalled = YES;
        }
    }
    
    return self;
}

- (void)test {
    NSLog(@"Hello World!");
}

@end

